<template>
  <div class="answer-wrapper">
    <div class="question-info-item">
      <div class="question-header">
        <img class="avatar" :src="question.asker.avatar" alt="" />
        <span class="name">{{ question.asker.nickname }}</span>
        <span class="price">￥{{ question.reward }}</span>
      </div>
      <div class="question-content">
        <div class="question-desc">
          <p class="question-text full-desc">{{ question.text }}</p>
          <image-previewer :images="question.attachments"></image-previewer>
          <div class="question-tags">
            <span v-if="question.purpose" class="tag-item tag-red">{{ question.purpose }}</span>
            <span v-if="question.catalog" class="tag-item">{{ question.catalog.name }}</span>
          </div>
          <span class="ask-time">{{ question.pastTimeStr }}提问</span>
        </div>
      </div>
    </div>
    <div class="answer-content">
      <van-field v-if="question.type" v-model="text" type="textarea" placeholder="对用户的作品添加文字回复" rows="5">
        <span class="van-field__counter">{{ counter }}</span>
      </van-field>
      <audio-recorder :cacheAudio='audio' @audioChanged="updateAudio"></audio-recorder>
      <image-uploader :initImages="images" v-if="question.type" @imageChanged="updateImages" ></image-uploader>
    </div>
    <div class="answer-footer">
      <button @click="cancel" class="cancel-btn">取消</button>
      <button @click="submit" class="confirm-btn">提交</button>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import qs from 'qs'
import util from '@/util/util'
import wx from 'weixin-js-sdk'

import ImageUploader from '@/components/imageUploader'
import AudioRecorder from '@/components/audioRecorder'

import { mapGetters } from 'vuex'

Vue.component(ImageUploader.name, ImageUploader)
Vue.component(AudioRecorder.name, AudioRecorder)

export default {
  name: 'Answer',
  data () {
    return {
      text: '',
      images: [],
      audio: null,
      question: this.$route.params.question,
    }
  },
  computed: {
    ...mapGetters([
      'answers',
    ]),
    counter: function() {
      var textCount = this.text.length
      return textCount + '/140'
    }
  },
  watch: {
    text: function() {
      this.storeAnswer()
    }
  },
  beforeCreate () {
    var webUrl = window.location.href
    var jsApiList = [
       "chooseImage",
       "previewImage",
       "uploadImage",
       "startRecord",
       "stopRecord",
       "onVoiceRecordEnd",
       "playVoice",
       "pauseVoice",
       "stopVoice",
       "onVoicePlayEnd",
       "uploadVoice"
    ]
    if (util.isAndroid()) {
      var that = this
      setTimeout(function() {
        that.SDKRegister(that, webUrl, jsApiList)
      }, 500)
    }
  },
  created() {
    this.initCacheAnswer()
  },
  methods: {
    cancel: function() {
      var answer = {
        'question': this.question.id,
        'text': this.text,
        'audio': this.audio,
        'images': this.images
      }
      var payload = { answer: answer }
      this.$store.dispatch('removeQuestionAnswer', payload)
      this.$router.go('-1')
    },
    initCacheAnswer() {
      var cacheAnswer = null
      for (var i=0; i<this.answers.length; i++) {
        var item = this.answers[i]
        if (item.question == this.question.id) {
          console.log(item.audio)
          this.text = item.text
          this.audio = item.audio
          this.images = item.images
          break
        }
      }
    },
    submit: function() {
      if (!this.audio) {
        return this.$toast.fail('请先录音回答')
      }
      var mediaIds = []
      this.images.forEach(function(img) {
        mediaIds.push(img.serverId)
      })
      var media_ids = mediaIds.join(',')
      var params = {
        'question': this.question.id,
        'text': this.text,
        'audio_id': this.audio.serverId,
        'audio_length': this.audio.duration,
        'media_ids': media_ids
      }
      this.$toast.loading()
      var that = this
      // 调用登陆接口
      this.axios.post('/dianping/answer/', qs.stringify(params))
      .then(function (res) {
        that.$toast.clear()
        if (res.status >= 200 && res.status < 300) {
          console.log(res.data)
          var answer = {
            'question': that.question.id,
            'text': that.text,
            'audio': that.audio,
            'images': that.images
          }
          var payload = { answer: answer }
          that.$store.dispatch('removeQuestionAnswer', payload)
          var localAnswer = {
            'id': res.data.id,
            'localId': that.audio.localId
          }
          var load = { answer: localAnswer }
          that.$store.dispatch('saveLocalAnswer', load)
          that.$toast.success('回答成功')
          that.$router.go('-1')
        } else {
          return that.$toast.fail(res.msg)
        }
      })
      .catch(function (error) {
        that.$toast.clear()
        if (error.response) {
          that.$toast.fail(error.response.data.detail)
        } else {
          that.$toast.fail('请求出错')
        }
      })
    },
    updateAudio(audio) {
      this.audio = audio
      this.storeAnswer()
    },
    updateImages(images) {
      // 更新图片文件列表
      this.images = images
      this.storeAnswer()
    }, 
    storeAnswer() {
      var answer = {
        'question': this.question.id,
        'text': this.text,
        'audio': this.audio,
        'images': this.images
      }
      var payload = { answer: answer }
      console.log(payload)
      this.$store.dispatch('setQuestionAnswer', payload)
    }
  }
}

</script>

<style lang="scss">
  @import '../../assets/style/const.scss';
  .answer-content {
    margin-top: 5px;
    margin-bottom: 60px;
  }
  .answer-title {
    height: 41px;
    width: 100%;
    background: #fff;
    color: $color-text-normal;
    text-align: center;
    span {
      height: 41px;
      line-height: 41px;
      font-size: .7rem;
    }
  }

  .answer-footer {
    position: fixed;
    bottom: 0;
    height: 50px;
    width: 100%;
    font-size: 0;
    .cancel-btn {
      font-size: 14px;
      width: 50%;
      height: 100%;
      box-sizing: border-box;
      background: #fff;
      color: $color-text-strong;
      border: none;
      cursor: pointer;
    }
    .confirm-btn {
      font-size: 14px;
      width: 50%;
      height: 100%;
      box-sizing: border-box;
      background: $color-yellow;
      color: #fff;
      border: none;
      cursor: pointer;
    }
  }
</style>
